<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParam.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="inputValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="getTree"
          :data="depts"
          :props="defaultProps"
          :highlight-current="true"
          default-expand-all
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'AddEmployees'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column align="center" prop="staffPhoto" label="头像" width="40px">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="36" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="120px" />
          <el-table-column prop="mobile" label="手机号" sortable width="120px" />
          <el-table-column prop="workNumber" label="工号" sortable width="120px" />
          <el-table-column align="center" prop="formOfEmployment" label="聘用形式" width="80px">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">零时</span>
              <span v-else>外包</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="departmentName" label="部门" width="120px" />
          <el-table-column align="center" prop="timeOfEntry" label="入职时间" width="120px" />
          <el-table-column align="center" label="操作" width="200px">
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="getEnableRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height:60px">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :page-size="queryParam.pagesize"
            :current-page="queryParam.page"
            @current-change="currentPage"
          />
        </el-row>
      </div>
    </div>
    <!-- 角色权限授予弹层 -->
    <el-dialog
      title="角色权限分配"
      :visible.sync="showRoleDialog"
    >
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col>
          <div style="text-align: center">
            <el-button type="primary" @click="allotEmployeePermission">确认</el-button>
            <el-button @click="showRoleDialog = false">取消</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- excel文件导入导出弹层组件 -->
    <importExcelShow :show-excel-dialog.sync="showExcelDialog" @updateFlit="getEmployeesList" />
  </div>
</template>
<script>
import importExcelShow from './importExcelShow.vue'
import { transListToTreeData } from '@/utils/index'
import { getDepartment } from '@/api/department'
import { getEmployeesList, exportExcel, delEmployee, getEnableRole, getEmployeeDetail, allotEmployeePermission } from '@/api/employee'
import fileSaver from 'file-saver'
export default {
  name: 'Employee',
  components: {
    importExcelShow
  },
  data() {
    return {
      staffID: null, // 角色按钮点击后获取的ID
      roleIds: [], // 用于接收双向绑定的值 item.id
      roleList: [], // 启用权限的角色列表
      showRoleDialog: false, // 控制角色分配权限组件的显示隐藏
      showExcelDialog: false, // 控制excel文件上传模态框显示隐藏
      depts: [], // 角色树形数据
      list: [], // 角色信息列表
      total: null, // 总页数
      defaultProps: { // 树形结构
        children: 'children',
        label: 'name'
      },
      queryParam: {
        departmentId: null, // 点击元素的ID
        page: 1, // 当前页数
        pagesize: 10, // 每页显示多少条数据
        keyword: ''
      }
    }
  },
  created() {
    this.getDepartment()
    this.getEmployeesList()
  },
  methods: {
    async getDepartment() {
      // 发起获取部门列表请求
      const res = await getDepartment()

      this.depts = transListToTreeData(res.data.data, 0) // 获取员工数据到depts
      this.queryParam.departmentId = this.depts[0].id // 获取第一个元素的ID，用来渲染打开页面时的默认选中
      this.$nextTick(() => {
        this.$refs.getTree.setCurrentKey(this.queryParam.departmentId)
      })
    },
    selectNode(node) { // 点击部门后，设置当前点击部门的id
      this.queryParam.departmentId = node.id
      this.queryParam.page = 1 // 点击新的部门后重置页数
      this.getEmployeesList()
    },
    async getEmployeesList() { // 获取员工列表数据
      const res = await getEmployeesList(this.queryParam)
      this.list = res.data.data.rows // 获取员工数据
      this.total = res.data.data.total // 获取总页数
    },
    currentPage(page) {
      this.queryParam.page = page // 设置当前页码
      this.getEmployeesList()
    },
    inputValue() {
      this.queryParam.page = 1 // 切回第一页，让数据在第一页展示
      clearTimeout(this.time) // 实现防抖功能
      this.time = setTimeout(() => {
        this.getEmployeesList() // 调用获取员工列表的函数，实现模糊查询
      }, 500)
    },
    async exportExcel() { // 导出数据
      const res = await exportExcel()
      fileSaver.saveAs(res, '员工信息表.xlsx') // 下载二进制文件
    },
    async delEmployee(id) { // 删除员工
      await delEmployee(id)
      await this.getEmployeesList() // 重新获取员工数据渲染
      if (this.list.length === 1 && this.queryParam.page > 1) { // 删除到最后一页，自动往前进一页
        this.queryParam.page--
      }
      this.$message.success('删除员工成功')
    },
    async getEnableRole(id) { // 获取已启用的角色列表
      this.staffID = id // 存储角色按钮点击后获取的ID
      const res = await getEnableRole() // 获取已启用角色的列表
      this.roleList = res.data.data
      const data = await getEmployeeDetail(id) // 获取点击元素的勾选项 ID
      this.roleIds = data.data.data.roleIds
      this.showRoleDialog = true // 因为获取已经拥有的角色是一个异步的过程，如果弹层显示在前，会出现卡顿的效果
    },
    async allotEmployeePermission() { // 分配权限请求
      await allotEmployeePermission({ id: this.staffID, roleIds: this.roleIds })
      this.$message.success('用户分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
